<template>
  <div class="login-wrap" :class="classObj">
    <div class="ms-login col flex">
      <div class="ms-login-info center align_center flex">
        <img src="../assets/loginImgs/krlogo.png" />
        <p>系统模板</p>
      </div>

      <template v-if="showDD">
        <div class="dd">
          <!-- <iframe :src="iframeUrl" scrolling="no"></iframe> -->
          <iframe :src="iframeUrl" frameborder="0" scrolling="no"></iframe>
          <div class="mask_layer" v-if="!showMask">
            <LoadingOutlined />
          </div>
          <div class="operation back-login">
            <span></span>
            <span @click="switchLogin(1)">返回账号登录</span>
          </div>
        </div>
      </template>

      <template v-else>
        <a-form
          ref="formRef"
          class="info-form center align_center column flex"
          layout="inline"
          :model="formState"
          @finish="handleFinish">
          <div class="login-title margin-bottom10">
            {{ userType === 1 ? '账号登录' : '超管账号登录' }}
          </div>

          <a-form-item
            name="staff_phone"
            :rules="[
              { required: true, message: '请输入你的账号!', trigger: 'change' }
            ]">
            <a-input
              v-model:value="formState.staff_phone"
              placeholder="请输入账号">
              <template #prefix
                ><UserOutlined style="color: rgba(0, 0, 0, 0.25)"
              /></template>
            </a-input>
          </a-form-item>

          <a-form-item
            name="staff_password"
            :rules="[
              { required: true, message: '请输入你的密码!', trigger: 'change' }
            ]">
            <a-input
              v-model:value="formState.staff_password"
              type="password"
              placeholder="请输入密码">
              <template #prefix
                ><LockOutlined style="color: rgba(0, 0, 0, 0.25)"
              /></template>
            </a-input>
          </a-form-item>

          <a-form-item
            v-if="userType === 2"
            name="sms_code"
            :rules="[
              { required: true, message: '请输入验证码!', trigger: 'change' }
            ]">
            <div class="super-form center align_center flex">
              <a-input
                v-model:value="formState.sms_code"
                placeholder="请输入验证码"></a-input>
              <a-button
                class="super_code_btn margin-left16"
                :loading="loading"
                type="primary"
                @click="getCode"
                v-if="codeShow">
                获取验证码
              </a-button>
              <a-button v-else disabled> {{ count }}s </a-button>
            </div>
            <p class="code-result" v-if="showResult">{{ codeResult }}</p>
          </a-form-item>

          <div class="operation" v-show="userType === 1">
            <span @click="switchLogin(2)">超管账号登录</span>
            <span @click="ddLogin">钉钉登录</span>
          </div>

          <a-form-item>
            <a-button :loading="loading" type="primary" html-type="submit">
              登录
            </a-button>
          </a-form-item>

          <div class="operation back-login" v-show="userType === 2">
            <span></span>
            <span @click="switchLogin(1)">返回账号登录</span>
          </div>
        </a-form>
      </template>
    </div>
  </div>
</template>

<script>
import { user, ding } from 'api'
import { ding_url, system_code } from 'api/config'
import { setStore } from '@/utils/util'

import ResizeMixin from '@/mixins/ResizeHandler'
import { mapMutations, mapState } from 'vuex'
import {
  LoadingOutlined,
  UserOutlined,
  LockOutlined
} from '@ant-design/icons-vue'

export default {
  components: {
    LoadingOutlined,
    UserOutlined,
    LockOutlined
  },
  data: function () {
    const hasErrors = (fieldsError) => {
      return Object.keys(fieldsError).some((field) => fieldsError[field])
    }
    return {
      hasErrors,
      // 用户 1、账号 2、超管
      userType: 1,

      formState: {
        staff_phone: '', //
        staff_password: '', //
        sms_code: ''
      },
      formRef: null,

      showDD: false,
      iframeUrl: '',
      showMask: false,

      // 验证码提示
      codeResult: '',
      showResult: false,
      codeShow: true, //获取验证码倒计时
      timer: null, //定时器
      count: '' //倒计时数字
    }
  },
  mixins: [ResizeMixin],
  computed: {
    ...mapState({
      loading: (state) => state.loading,
      device: (state) => state.device
    }),
    classObj() {
      return {
        mobile: this.device === 'mobile'
      }
    }
  },
  watch: {
    showDD() {
      this.showMask = !this.showDD
    }
  },
  mounted() {
    this.formRef = this.$refs.formRef
  },
  methods: {
    handleFinish() {
      this.formRef
        .validate()
        .then(async () => {
          let values = this.formState
          console.log('[ values ] >', values)
          // 假数据
          let userInfo = {
            staff_name: values.staff_phone,
            staff_id: 1,
          }
          setStore('token', 99999)
          setStore('userInfo', {
            staff_id: userInfo.staff_id,
            username: userInfo.staff_name,

          })
          window.top.location.reload()

          // if (this.userType === 1) {
          //   let res = await user.login({
          //     ...values,
          //     staff_password: values.staff_password.replace(
          //       /(^\s*)|(\s*$)/g,
          //       ''
          //     )
          //   })

          //   if (res.state === 1) {
          //     this.showDD = true
          //     let userInfo = res.data
          //     setStore('userLoginInfo', userInfo)

          //     // 未绑定钉钉，申请二维码
          //     if (!userInfo.dd_no) {
          //       this.$message.error('请先绑定您的钉钉账户')
          //       let ddRes = await ding.applyDD(
          //         {
          //           type: 1,
          //           system_code: system_code,
          //           staff_id: userInfo.staff_id,
          //           // redirectUrl: "http://183.3.158.125:9804/#/dingding",
          //           // redirectUrl: "http://192.168.0.83:9804/#/dingding",
          //           redirectUrl: ding_url + '/#/dingding'
          //         },
          //         userInfo.staff_token
          //       )
          //       setTimeout(() => {
          //         this.showMask = true
          //       }, 500)
          //       if (ddRes.code && ddRes.state === 1) {
          //         this.iframeUrl = ddRes.data.scan_url
          //         // 登录方式 1账号密码 2钉钉扫码
          //         setStore('loginType', 1)
          //       } else {
          //         this.$message.error(res.msg)
          //       }
          //     } else {
          //       this.$message.success(res.msg)

          //       setStore('token', userInfo.staff_token)

          //       setStore('userInfo', {
          //         username: userInfo.staff_name,
          //         staff_id: userInfo.staff_id
          //       })

          //       setStore('rolesArr', res.data.permission)

          //       this.setInfo({ username: userInfo.staff_name })

          //       window.top.location.reload()
          //     }
          //   } else {
          //     this.$message.error(res.msg)
          //   }
          // } else if (this.formState.sms_code) {
          //   // 超管登录
          //   let res = await user.superAdminLogin(values)

          //   if (res.state === 1) {
          //     let userInfo = res.data
          //     this.showResult = false
          //     this.$message.success(res.msg)

          //     setStore('token', userInfo.staff_token)

          //     setStore('userInfo', {
          //       username: userInfo.staff_name,
          //       staff_id: userInfo.staff_id
          //     })

          //     setStore('rolesArr', res.data.permission)
          //     this.setInfo({ username: userInfo.staff_name })
          //     window.top.location.reload()
          //   } else {
          //     this.showResult = true
          //     this.codeResult = res.msg
          //     this.$message.error(res.msg)
          //   }
          // } else {
          //   this.codeResult = '验证码不能为空'
          //   this.showResult = true
          // }
        })
        .catch((error) => {
          console.log(error)
        })
    },

    // 获取验证码
    getCode(e) {
      e.preventDefault()

      this.form.validateFields(async (err, values) => {
        if (!err) {
          let res = await user.getCode({
            ...values,
            sms_code: undefined
          })

          if (res.code && res.state === 1) {
            this.$message.success(res.msg)

            this.showResult = false

            const TIME_COUNT = 60
            if (!this.timer) {
              this.count = TIME_COUNT
              this.codeShow = false
              this.timer = setInterval(() => {
                if (this.count > 0 && this.count <= TIME_COUNT) {
                  this.count--
                } else {
                  this.codeShow = true
                  clearInterval(this.timer)
                  this.timer = null
                }
              }, 1000)
            }
          } else {
            this.showResult = true

            this.codeResult = res.msg

            this.$message.error(res.msg)
          }
        }
      })
    },

    // 钉钉登录 - 扫码
    async ddLogin() {
      this.showDD = true
      let ddRes = await ding.applyDD({
        type: 2,
        system_code: system_code,
        // redirectUrl: "http://183.3.158.125:9804/#/dingding",
        // redirectUrl: "http://192.168.0.83:9804/#/dingding",
        redirectUrl: ding_url + '/#/dingding'
      })

      if (ddRes.code && ddRes.state === 1) {
        this.iframeUrl = ddRes.data.scan_url
        setTimeout(() => {
          this.showMask = true
        }, 500)
        setStore('loginType', 2)
      } else {
        this.$message.error(ddRes.msg)
      }
    },

    // 切换登录方式
    switchLogin(index) {
      this.showDD = false
      this.showResult = false
      this.userType = index

      this.formRef.resetFields()
    },

    ...mapMutations({
      setInfo: 'setInfo',
      setRoles: 'setRoles',
      setToken: 'setToken',
      setPowers: 'setPowers'
    })
  }
}
</script>

<style lang="less" scoped>
.stat-circle {
  svg {
    height: 34px;
    width: 34px;
    transform: rotate(90deg) scale(-1, -1);

    path {
      opacity: 0;
    }
  }

  .stat-circle_body {
    display: flex;
    flex-direction: space-around;
    align-items: center;
    height: 80px;
  }

  .stat-circle_done {
    .stat-circle_path {
      stroke: #16d0d0;
    }
    .stat-circle_mark {
      stroke: #16d0d0;
      opacity: 1;
    }
  }
  @keyframes path {
    100% {
      stroke-dasharray: 95, 95;
      stroke-dashoffset: 95;
    }
  }
  .stat-circle_bg {
    cx: 17;
    cy: 17;
    r: 15;
    stroke: #efefef;
    stroke-width: 2;
    fill: none;
  }
  .stat-circle_path {
    cx: 17;
    cy: 17;
    r: 15;
    stroke: #5116d0;
    stroke-width: 2;
    stroke-linecap: round;
    fill: none;
    animation: path 1.5s ease reverse;
  }
  .stat-circle_mark {
    fill: none;
    stroke-width: 2;
    stroke-linecap: round;
    stroke-linejoin: round;
  }
}

.stat-chart {
  svg {
    width: 100%;
    height: 80px;
  }

  .stat-chart_bg {
    fill: url(#gradient);
    stroke: none;
  }

  .stat-chart_path {
    stroke: #5116d0;
    stroke-dasharray: 500, 500;
    fill: none;
    stroke-width: 2;
    stroke-linejoin: miter;
    animation: path2 1.5s ease reverse;
  }

  @keyframes path2 {
    100% {
      stroke-dasharray: 0, 200%;
      stroke-dashoffset: 0;
    }
  }
}

.login-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  background-image: url('../assets/loginImgs/login_bg.png');
  background-repeat: repeat;
  background-position: center;
}

.info-form {
  .login-title {
    color: rgba(61, 54, 54, 0.7);
    font-size: 16px;
    width: 100%;
    text-align: left;
    box-sizing: border-box;
  }

  .code-result {
    margin: 0;
    color: #f43d3d;
    font-size: 14px;
    height: 30px;
    line-height: 40px;
    text-align: left;
  }
}

.operation {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  margin-bottom: 10px;
  color: #1890ff;
  &.back-login {
    margin: 0;
  }
  span {
    cursor: pointer;
  }
}

.ant-form-item {
  margin-right: 0;
  margin-bottom: 10px;
}

.dd {
  z-index: 99;
  margin: 0 auto;
  padding: 0 10px 15px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  iframe {
    position: relative;
    left: -37px;
    width: 300px;
    height: 320px;
    background: #ffffff !important;
  }
  .mask_layer {
    position: absolute;
    width: 400px;
    height: 360px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }
}
</style>
